package com.example.extra.controller;

import com.example.extra.common.Constants;
import com.example.extra.vo.VerificationCodeVo;
import com.wf.captcha.SpecCaptcha;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Tag(name = "登录验证码图片")
@RestController
@RequestMapping("/api")
public class CaptchaController {

    private final RedisTemplate<String, String> redisTemplate; // 使用String序列化

    // 验证码在Redis中的前缀和过期时间(秒)
    private static final long CAPTCHA_EXPIRE_SECONDS = 120;
    public CaptchaController(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/code")
    @Operation(summary = "生成登录验证码图片")
    public VerificationCodeVo generateCaptcha() {
        // 生成验证码（宽130，高48，4位字符）
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        // 可以设置类型：纯数字、字母数字混合等:cite[7]
        // specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);

        String code = specCaptcha.text().toLowerCase(); // 生成文本并转为小写，方便比较:cite[3]
        String uuid = UUID.randomUUID().toString(); // 生成唯一标识:cite[3]

        // 存储到Redis，key为 "captcha:uuid"，值为验证码文本，设置过期时间:cite[3]
        redisTemplate.opsForValue().set(
                Constants.REDIS_CAPTCHA_PREFIX + uuid,
                code,
                CAPTCHA_EXPIRE_SECONDS,
                TimeUnit.MINUTES
        );
        VerificationCodeVo verificationCodeVo = new VerificationCodeVo();
        verificationCodeVo.setMsg("操作成功");
        verificationCodeVo.setUuid(uuid);
        verificationCodeVo.setCode("200");
        verificationCodeVo.setImg(specCaptcha.toBase64());
        verificationCodeVo.setCaptchaEnabled(true);
        return verificationCodeVo;
    }
}

